package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var wg sync.WaitGroup

func init() {
	//生成随机数并发安全保障
	rand.Seed(time.Now().UnixNano())
}

func main() {
	court := make(chan int)
	wg.Add(2)

	go player("Nadal", court)
	go player("Tom", court)

	//发球
	court <- 1

	//等待游戏结束
	wg.Wait()
}

func player(name string, court chan int) {
	defer wg.Done()

	for {
		//等待球被击过来，若通道被关闭，则对面丢球，我方赢了
		ball, ok := <-court
		if !ok {
			fmt.Printf("Player %s Won \n", name)
			return
		}

		//选随机数，判断我们是否丢球
		n := rand.Intn(100)
		if n%13 == 0 { // 两数的余数
			fmt.Printf("Player %s Missed \n", name)
			close(court)
			return
		}

		//显示击球数，并将击球数+1
		fmt.Printf("Player %s Hit %d\n", name, ball)
		ball++

		//将球打向对手
		court <- ball
	}
}
